'use strict';
const cloud = require('wx-server-sdk');
const { uniID } = require('uni-id-common');

cloud.init();
const db = cloud.database();

exports.main = async (event, context) => {
  // 初始化uniID
  const uniIDIns = uniID.createInstance({ context });
  
  const { phone, code, newPassword } = event;
  
  // 参数验证
  if (!phone || !code || !newPassword) {
    return {
      code: 400,
      message: '请填写完整的信息'
    };
  }
  
  if (newPassword.length < 6) {
    return {
      code: 400,
      message: '密码至少需要6位'
    };
  }
  
  try {
    // 验证验证码
    const verifyCodeRes = await uniIDIns.verifySmsCode({
      phone,
      code,
      type: 'reset-pwd'
    });
    
    if (verifyCodeRes.code !== 0) {
      return verifyCodeRes;
    }
    
    // 重置密码
    const resetPwdRes = await uniIDIns.updatePwdByPhone({
      phone,
      newPassword
    });
    
    if (resetPwdRes.code !== 0) {
      return resetPwdRes;
    }
    
    // 记录密码修改日志
    await db.collection('userLogs').add({
      data: {
        phone,
        action: 'reset_password',
        create_time: new Date()
      }
    });
    
    return {
      code: 0,
      message: '密码重置成功'
    };
    
  } catch (error) {
    console.error('重置密码失败:', error);
    return {
      code: 500,
      message: '重置密码失败，请稍后重试'
    };
  }
};